package com.demo.com.controller;

import com.demo.com.highavailability.context.BusinessContextHolder;
import com.demo.com.highavailability.executor.IsolatedTaskExecutor;
import com.demo.com.highavailability.monitor.ThreadMonitor;
import com.demo.com.highavailability.proxy.ServiceRouterFactory;
import com.demo.com.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;

@RestController
@RequestMapping("/api/business")
public class BusinessController {

    private NotificationService notificationService;

    @Autowired
    private ServiceRouterFactory serviceRouterFactory;

    @PostConstruct
    public void init() {
        // 初始化服务代理
        notificationService = serviceRouterFactory.createServiceProxy(
            NotificationService.class,
            "emailNotificationService",
            "smsNotificationService"
        );
    }

    @PostMapping("/process")
    public String processBusiness(@RequestParam String businessId) {
        try {
            ThreadMonitor.startBusinessProcess();
            
            // 设置业务上下文
            BusinessContextHolder.setAttribute("businessId", businessId);
            
            // 执行核心业务
            executeCoreBusiness(businessId);
            
            // 在隔离线程中执行通知服务
            IsolatedTaskExecutor.executeInIsolation(() -> {
                notificationService.sendNotification("Processing business: " + businessId);
            });
            
            return "Business processed successfully: " + businessId;
        } finally {
            BusinessContextHolder.clear();
            ThreadMonitor.endBusinessProcess();
        }
    }

    private void executeCoreBusiness(String businessId) {
        System.out.println("Executing core business logic for: " + businessId);
        // 模拟核心业务处理
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}